﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace ZRT.RHPX.Core.Mvc.Filters
{
    /// <summary>
    /// 后台身份验证
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class DefaultAuthorize : AuthorizeAttribute
    {
        private string _AuthorizationFailView = "";//从配置文件或其他地方获取
        /// <summary>
        /// 授权失败时呈现的视图
        /// </summary>

        public string AuthorizationFailView
        {
            get { return this._AuthorizationFailView; }
            set { this._AuthorizationFailView = value; }
        }

        /// <summary>
        /// 重写
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            //获得url请求里的controller和action：
            string controllerName = filterContext.RouteData.Values["controller"].ToString().ToLower();
            string actionName = filterContext.RouteData.Values["action"].ToString().ToLower();

            //根据请求过来的controller和action去查询可以被哪些角色操作
            //查询数据库...
            this.Roles = ""; //有权限操作当前控制器和Action的角色id

            base.OnAuthorization(filterContext);
        }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext.User.Identity.IsAuthenticated)
            {
                string UserName = httpContext.User.Identity.Name;    //当前登录用户的用户名
                //查询当前用户是否拥有角色
                return true;
            }
            else
                return false;     //进入HandleUnauthorizedRequest 
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            filterContext.Result = new ViewResult { ViewName = AuthorizationFailView };
        }
    }
}
